const app = getApp()
var innerAudioContext, playurl = []

import { throttle } from '../../utils/throttle.js'
import { HiddenCall } from '../../request/api'
const request = new HiddenCall
import form_submit from '../../mixins/form_submit'
import filter from '../../mixins/filter'
// 跟进数据组织跳转
import { describeData } from '../../utils/method.js'
Page({
  /**
  *  电话详情页
  * - @author           王磊
  * - @date             2018-07-08
  *  headerList        电话详情tab
  *  isType              tab下标
  *  page                页数
  */
  mixins: [form_submit, filter],
  data: {
    headerList: [],
    isType: 0,
    page: 1,
    smsDetail: null
  },
  onLoad: function (options) {
    let model = JSON.parse(options.model)
    model.called ? this.data.headerList = [{ name: "通话" }] : this.data.headerList = [{ name: "短信" }]
    // 获取详情数据，是否可以回拨电话
    this.setData({
      telData: model,
      isLimiteCall: model.isLimiteCall ? model.isLimiteCall:'',
      headerList: this.data.headerList
    })
    // 汇集数据获取通话列表
    this.telDetail = {
      // 获取手机号
      "callId": model.callId,
      "tactics": "callServiceImpl"
    }
    // 播放通话录音
    innerAudioContext = wx.createInnerAudioContext()
    // 播放通话结束
    innerAudioContext.onEnded(() => {
      // 停止播放
      this.stopTelRecord()
    })
    if (this.data.telData.called) {
      this.callDetailList(this.telDetail)
      wx.setNavigationBarTitle({
        title: "通话详情"
      })
    } else {
      this.smsDetailList()
      wx.setNavigationBarTitle({
        title: "短信详情"
      })
    }
    wx.showNavigationBarLoading()
    this.getHeight()
  },
  onUnload () {
    // 停止播放
    this.stopTelRecord()
  },
  /**
   * 电话详情列表
   * author wl
   */
  callDetailList: function(model) {
    // 传入token和参数
    request.queryDetail(model).then(res => {
      this.setData({ callDetail: res })
      wx.hideNavigationBarLoading() 
      wx.stopPullDownRefresh()
    })
  },
  smsDetailList: function () {
    // 传入token和参数
    let model = {
      "customerPhone": this.data.telData.customerPhone,
      "page": 1,
      "pageSize": 15,
      "resourceCode": this.data.telData.resourceCode
    }
    this.data.telData.resourceCode ? request.queryMessage(model).then(res => {
      this.setData({ 
        smsDetail: res.recordingModels.content,
        count: res.recordingModels.count
      })
      wx.hideNavigationBarLoading()
      wx.stopPullDownRefresh()
    }):""
  },
  /**
   * 点击展开||收起更多文字描述||跟进
   * author wl
   */
  lookInfo(e) {
    // 获取通话列表数据当前索引
    let data = this.data.callDetail.callRecordsModelList
    let index = e.currentTarget.dataset.index
    // 点击当前展开通话列表描述跟进文字，其他隐藏
    for (let i = 0; i < data.length; i++) {
      index === i ? data[i].isunfold = !data[i].isunfold : data[i].isunfold = false
    }
    // 详情列表数据
    this.setData({
      callDetail: this.data.callDetail
    })
  },
  /**
 * 点击切换通话||短信
 * author wl
 */
  writeDescription(e) {
    if (!this.data.telData.called) {
      this.smsDetailList()
    } else {
      this.telDetail.called ? this.callDetailList(this.telDetail):''
    }
  },
  phoneList: function () {
    // 判断是房源还是客源
    let code = this.data.telData.resourceCode
    request.lookPhone(code, "hide").then((res) => {
      this.setData({ listPhone: res })
      this.setData({ show: true, callBtn: true })
    })
  },
  /**
     * 房客源显示电话拨打弹框查看手机号
     * author wl
     */
  sendMessage: function () {
    // 判断是房源还是客源
    let code = this.data.telData.resourceCode
    this.setData({ messageShow: true, messageCallBtn: true })
    request.messageNum(code, "hide").then((res) => {
      this.setData({
        message: JSON.parse(JSON.stringify(res)),
        showMessage: res
      })
      this.data.showMessage.forEach((el, i) => {
        this.data.showMessage[i].realNumber = el.realNumber.substr(0, 3) + '号段'
      })
      this.setData({ showMessage: this.data.showMessage })
    })
  },
  /**
  * 进入短信详情
  * author wl
  */
  entrSms: throttle(function() {
    // 短信详情参数，以便切换不同页面
    let data = {
      callType: "sms",
      detailType: "allDetail",
      callModel: this.data.telData
    }
    // 进入短信详情带入参数
    wx.navigateTo({
      url: `../mailing_detail/index?model=${JSON.stringify(data)}`
    })
  }, 2000),
  /**
   * 短信发送
   * @author
   */
  makeMessage(e) {
    // 设置短信详情标志
    let data = {
      callType: "sms",
      detailType: '',
      utypeCode: (this.data.telData.resourceType === "出售" || this.data.telData.resourceType === "出租")?0:1,
      code: this.data.telData.resourceCode,
      sendTel: this.data.telData.customerPhone,
      resourcetype: this.data.telData.resourceType || this.data.telData.resourceType
    }
    wx.navigateTo({
      url: `../mailing_detail/index?model=${JSON.stringify(data)}`
    })
  },
  /**
  * 电话详情拨打电话
  * author dzl
  */
  makePhone: throttle(function (e) {
    // 检测是否有遗留跟进未填写,有的话完善
    request.followFinished().then((res) => {
      if (res.result) {
        // 汇集数据
        describeData('phone_list', res, true, 1)
      } else {
        // 下面为直接打电话的跟进数据汇集
        let code = e.currentTarget.dataset.resourcecode,
          // 拿到房客编号
          resourceCode = this.data.telData.resourceCode
        // 拿到手机号
        var called, caller
        if (this.data.telData.calltype) {
          called = this.data.telData.calltype === -1 ? this.data.telData.caller : this.data.telData.called
          caller = this.data.telData.calltype === -1 ? this.data.telData.called : this.data.telData.caller
        } else {
          called = this.data.telData.customerPhone
        }
        request.directCall({ caller, called, resourceCode }).then(res => {
          // 调用微信api进行拨打电话
          this.phoneCall(res, code, 1)
        })
      }
    })
  }, 2000),
  /**
  * 下拉刷新电话详情数据
  * author dzl
  */
  onPullDownRefresh() {
    // 设置初始页数数据
    wx.showNavigationBarLoading()
    this.setData({ page: 1 })
    this.telDetail.page = this.data.page
    // 调用通话列表接口
    this.callDetailList(this.telDetail)
  },
  /**
   * 电话详情上拉加载数据
   * author dzl
   */
  onReachBottom() {
    // 设置加载页数
    wx.showNavigationBarLoading()
    this.data.page += 1
    if (this.data.telData.called) {
      // 设置调用接口传参页数
      this.telDetail.page = this.data.page
      request.queryDetail(this.telDetail).then(res => {
        // 循环新数据加入渲染model
        this.data.callDetail.callRecordsModelList = [...this.data.callDetail.callRecordsModelList, ...res.callRecordsModelList]
        // 赋值通话列表
        this.setData({ callDetail: this.data.callDetail })
        wx.hideNavigationBarLoading()
      })
    }else {
      if (this.data.smsDetail.length === this.data.count) {
        wx.hideNavigationBarLoading()
        return
      }
      let model = {
        "customerPhone": this.data.telData.customerPhone,
        "page": this.data.page,
        "pageSize": 15,
        "resourceCode": this.data.telData.resourceCode
      }
      request.queryMessage(model).then(res => {
        this.data.smsDetail = [...this.data.smsDetail, ...res.recordingModels.content]
        this.setData({ 
          smsDetail: this.data.smsDetail,
          count: res.recordingModels.count
        })
        wx.hideNavigationBarLoading()
      })
    }
  },
  /**
    * 播放房客源详情通话录音
    * author wl
    */
  playTelRecord(e) {
    // 播放地址
    let url = e.currentTarget.dataset.url
    // 开始播放
    innerAudioContext.src = url
    innerAudioContext.play()
    this.setData({ play: true })
  },
  /**
 * 停止播放房客源详情通话录音
 * author wl
 */
  stopTelRecord(e) {
    // 停止播放
    innerAudioContext.stop()
    // 数据更新
    this.setData({ play: false })
  } ,
  clickMask () {
    this.setData({ messageShow: false, messageCallBtn: false })
  },
  /**
   * 进入转文字详情
   * @author wl
   */
  enterText(e) {
    let voice = { voiceUrl: e.currentTarget.dataset.item, duration: e.currentTarget.dataset.time }
    wx.navigateTo({
      url: `../transfer_text/index?data=${JSON.stringify({ data: this.data.telData, voice })}`,
    })
  }
})